<template>
  <view class="edit-profile-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">编辑资料</block>
    </cu-custom>

    <!-- 编辑表单 -->
    <view class="form-container bg-white margin-top">
      <view class="form-section">
        <view class="section-title padding">
          <text class="text-lg text-bold">基本信息</text>
        </view>

        <view class="form-item">
          <view class="form-label">
            <text class="text-red">*</text>
            <text>姓名</text>
          </view>
          <input
            v-model="formData.empName"
            class="form-input"
            placeholder="请输入姓名"
          />
        </view>

        <view class="form-item">
          <view class="form-label">性别</view>
          <picker
            :value="genderIndex"
            :range="genderOptions"
            @change="onGenderChange"
          >
            <view class="form-input picker-input">
              <text>{{ genderOptions[genderIndex] || "请选择性别" }}</text>
              <text class="cuIcon-right text-gray"></text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <view class="form-label">手机号</view>
          <input
            v-model="formData.phone"
            class="form-input"
            placeholder="请输入手机号"
            type="number"
          />
        </view>

        <view class="form-item" v-if="isEmployeeLogin">
          <view class="form-label">员工编号</view>
          <input
            v-model="formData.empNo"
            class="form-input"
            placeholder="请输入员工编号"
          />
        </view>

        <view class="form-item">
          <view class="form-label">所属部门</view>
          <input
            v-model="formData.departName"
            class="form-input"
            placeholder="请输入所属部门"
            disabled
          />
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="button-section margin-top">
      <button
        class="cu-btn bg-blue lg block margin"
        @click="saveProfile"
        :loading="saving"
      >
        {{ saving ? "保存中..." : "保存修改" }}
      </button>
    </view>
  </view>
</template>

<script>
import authService from "../../src/services/auth.js";
import { http } from "@/common/service/service.js";
import { USER_INFO } from "@/common/util/constants.js";

export default {
  data() {
    return {
      formData: {
        id: "",
        empName: "",
        empNo: "",
        phone: "",
        sex: null,
        departName: "",
      },
      genderOptions: ["男", "女"],
      genderIndex: 0,
      loginType: "",
      saving: false,
    };
  },

  computed: {
    isEmployeeLogin() {
      return this.loginType === "employee";
    },

    isAdminLogin() {
      return this.loginType === "admin";
    },
  },

  onLoad() {
    this.initPage();
  },

  methods: {
    initPage() {
      this.loginType = uni.getStorageSync("erp_login_type") || "";
      this.loadUserInfo();
    },

    loadUserInfo() {
      const userInfo = authService.getCurrentUser() || {};

      this.formData = {
        id: userInfo.id || "",
        empName: userInfo.empName || userInfo.realname || "",
        empNo: userInfo.empNo || userInfo.username || "",
        phone: userInfo.phone || "",
        sex: userInfo.sex || null,
        departName: userInfo.departName || "",
      };

      // 设置性别选择器
      if (userInfo.sex === 1) {
        this.genderIndex = 0; // 男
      } else if (userInfo.sex === 2) {
        this.genderIndex = 1; // 女
      }
    },

    onGenderChange(e) {
      this.genderIndex = e.detail.value;
      this.formData.sex = parseInt(e.detail.value) + 1; // 1-男，2-女
    },

    async saveProfile() {
      if (!this.validateForm()) {
        return;
      }

      this.saving = true;

      try {
        let response;

        if (this.isEmployeeLogin) {
          // 员工调用员工接口
          response = await http.put("/sys/employee/edit", this.formData);
        } else {
          // 管理员调用用户接口
          const userData = {
            id: this.formData.id,
            realname: this.formData.empName,
            username: this.formData.empNo,
            phone: this.formData.phone,
            sex: this.formData.sex,
          };
          response = await http.put("/sys/user/edit", userData);
        }

        if (response.data.success) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });

          // 更新本地存储的用户信息
          this.updateLocalUserInfo();

          // 延迟返回上一页，并触发页面刷新
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
              success: () => {
                // 通过事件总线通知个人信息页面刷新数据
                uni.$emit("refreshProfile");
              },
            });
          }, 1500);
        } else {
          uni.showToast({
            title: response.data.message || "保存失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("保存用户信息失败:", error);
        uni.showToast({
          title: "保存失败，请重试",
          icon: "none",
        });
      } finally {
        this.saving = false;
      }
    },

    validateForm() {
      if (!this.formData.empName.trim()) {
        uni.showToast({
          title: "请输入姓名",
          icon: "none",
        });
        return false;
      }

      if (this.isEmployeeLogin && !this.formData.empNo.trim()) {
        uni.showToast({
          title: "请输入员工编号",
          icon: "none",
        });
        return false;
      }

      if (this.formData.phone && !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: "请输入正确的手机号",
          icon: "none",
        });
        return false;
      }

      return true;
    },

    updateLocalUserInfo() {
      const currentUser = uni.getStorageSync(USER_INFO);
      const updatedUser = {
        ...currentUser,
        empName: this.formData.empName,
        realname: this.formData.empName,
        empNo: this.formData.empNo,
        username: this.formData.empNo,
        phone: this.formData.phone,
        sex: this.formData.sex,
      };

      // 更新认证服务中的用户信息
      authService.setUserInfo(updatedUser);

      // 更新本地存储的用户信息
      uni.setStorageSync(USER_INFO, updatedUser);
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.form-container {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
}

.section-title {
  border-bottom: 1rpx solid #f0f0f0;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f8f9fa;

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  width: 160rpx;
  font-size: 32rpx;
  color: #333;
  flex-shrink: 0;

  .text-red {
    margin-right: 8rpx;
  }
}

.form-input {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  text-align: right;

  &[disabled] {
    color: #999;
  }
}

.picker-input {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #333;

  .cuIcon-right {
    margin-left: 16rpx;
    font-size: 24rpx;
  }
}

.button-section {
  padding: 0 24rpx;
}
</style>
